package com.lipaluma.io.xml;
import static org.joox.JOOX.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import org.joox.Match;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.lipaluma.exceptions.CsvParserException;
import com.lipaluma.io.Row;
import com.lipaluma.io.SourceReader;

public class XmlReader implements SourceReader {

	private Document root;
	private Match currentElement;
	private String path;
	private int currentLine;
	
	public XmlReader(InputStream input, String path) {
		this.path = path;
		try {
			this.root = $(input).document();
		} catch (SAXException e) {
			throw new CsvParserException("The entry input xml is malformed", e);
		} catch (IOException e) {
			throw new CsvParserException("The entry input xml can't be opened", e);
		}
	}
	public XmlReader(Reader input, String path) {
		this.path = path;
		try {
			this.root = $(input).document();
		} catch (SAXException e) {
			throw new CsvParserException("The entry input xml is malformed", e);
		} catch (IOException e) {
			throw new CsvParserException("The entry input xml can't be opened", e);
		}
	}
	public XmlReader(String input, String path) {
		this.path = path;
		this.root = $(input).document();
	}
	
	@Override
	public int getCurrentLineNumber() {
		return currentLine;
	}

	@Override
	public boolean hasNext() {
		return currentLine < currentElement.size();
	}

	@Override
	public Row next() {
		currentLine ++;
		if(currentLine == 0) {
			currentElement = $(root).children(path).first();
		} else
			currentElement = currentElement.next();
		return new XmlRow(currentElement.get(0));
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub

	}

}
